extends Node

# AI难度等级
enum AIDifficulty {
	EASY,
	MEDIUM,
	HARD
}

# AI行动类型
enum AIAction {
	PLAY_CARD,
	ATTACK_HERO,
	ATTACK_UNIT,
	END_TURN
}

# AI配置
@export var difficulty: AIDifficulty = AIDifficulty.EASY
@export var thinking_time: float = 1.0
@export var max_actions_per_turn: int = 10

# AI决策权重
var action_weights = {
	AIAction.PLAY_CARD: 10,
	AIAction.ATTACK_HERO: 8,
	AIAction.ATTACK_UNIT: 6,
	AIAction.END_TURN: 1
}

# 卡牌价值评估权重
var card_value_weights = {
	"cost": -1.0,  # 费用越低越好
	"attack": 2.0,  # 攻击力越高越好
	"health": 1.5,  # 生命值越高越好
	"effect_value": 3.0  # 效果值越高越好
}

func _ready():
	# 根据难度调整权重
	adjust_weights_by_difficulty()

func adjust_weights_by_difficulty():
	"""根据难度调整AI权重"""
	match difficulty:
		AIDifficulty.EASY:
			# 简单AI更倾向于随机行动
			action_weights[AIAction.PLAY_CARD] = 8
			action_weights[AIAction.ATTACK_HERO] = 5
			action_weights[AIAction.ATTACK_UNIT] = 3
			thinking_time = 0.5
		AIDifficulty.MEDIUM:
			# 中等AI更平衡
			action_weights[AIAction.PLAY_CARD] = 10
			action_weights[AIAction.ATTACK_HERO] = 8
			action_weights[AIAction.ATTACK_UNIT] = 6
			thinking_time = 1.0
		AIDifficulty.HARD:
			# 困难AI更聪明
			action_weights[AIAction.PLAY_CARD] = 12
			action_weights[AIAction.ATTACK_HERO] = 10
			action_weights[AIAction.ATTACK_UNIT] = 8
			thinking_time = 1.5

func execute_turn(hand: Array[Control], board: Array[Control], mana: int, enemy_board: Array[Control], enemy_health: int):
	"""执行AI回合"""
	
	var actions_taken = 0
	
	while actions_taken < max_actions_per_turn:
		# 等待思考时间
		await get_tree().create_timer(thinking_time * 0.3).timeout
		
		# 决定下一个行动
		var action = decide_next_action(hand, board, mana, enemy_board, enemy_health)
		
		if action == null:
			break
		
		# 执行行动
		var success = execute_action(action, hand, board, mana, enemy_board, enemy_health)
		
		if not success:
			print("AI行动执行失败")
			break
		
		actions_taken += 1
		
		# 更新法力值（如果打出了卡牌）
		if action.type == AIAction.PLAY_CARD:
			mana -= action.card.cost

func decide_next_action(hand: Array, board: Array[Control], mana: int, enemy_board: Array[Control], enemy_health: int) -> Dictionary:
	"""决定下一个行动"""
	var possible_actions = []
	
	# 评估可打出的卡牌
	for card in hand:
		if card.cost <= mana:
			var action = {
				"type": AIAction.PLAY_CARD,
				"card": card,
				"score": evaluate_card_play(card, board, enemy_board, enemy_health)
			}
			possible_actions.append(action)
	
	# 评估可攻击的单位
	for unit in board:
		if unit and not unit.has_attacked_this_turn and not unit.has_summoning_sickness:
			# 攻击敌方英雄
			var attack_hero_action = {
				"type": AIAction.ATTACK_HERO,
				"attacker": unit,
				"target": null,
				"score": evaluate_attack_hero(unit, enemy_health)
			}
			possible_actions.append(attack_hero_action)
			
			# 攻击敌方单位
			for enemy_unit in enemy_board:
				if enemy_unit:
					var attack_unit_action = {
						"type": AIAction.ATTACK_UNIT,
						"attacker": unit,
						"target": enemy_unit,
						"score": evaluate_attack_unit(unit, enemy_unit)
					}
					possible_actions.append(attack_unit_action)
	
	# 如果没有好的行动，考虑结束回合
	if possible_actions.is_empty() or (possible_actions.size() == 1 and possible_actions[0].score < 2):
		return {"type": AIAction.END_TURN, "score": 0}
	
	# 选择得分最高的行动
	possible_actions.sort_custom(func(a, b): return a.score > b.score)
	
	# 添加一些随机性（根据难度）
	var randomness = 0.3 if difficulty == AIDifficulty.EASY else 0.1
	if randf() < randomness and possible_actions.size() > 1:
		return possible_actions[randi() % min(3, possible_actions.size())]
	
	return possible_actions[0] if not possible_actions.is_empty() else null

func evaluate_card_play(card: Control, board: Array[Control], enemy_board: Array[Control], enemy_health: int) -> float:
	"""评估打出卡牌的价值"""
	var score = 0.0
	
	# 基础价值评估
	score += card.attack * card_value_weights["attack"]
	score += card.health * card_value_weights["health"]
	score += card.cost * card_value_weights["cost"]
	score += card.effect_value * card_value_weights["effect_value"]
	
	# 卡牌类型特殊评估
	if card.card_type == "unit":
		# 单位卡：考虑战场空间
		if board.size() >= 7:
			score -= 10  # 战场已满，减分
		else:
			score += 2  # 增加战场存在感
	
	elif card.card_type == "spell":
		# 法术卡：根据效果评估
		match card.effect:
			"deal_damage":
				# 如果能击杀敌方英雄，优先级极高
				if card.effect_value >= enemy_health:
					score += 100
				else:
					score += card.effect_value * 2
			"heal":
				score += card.effect_value * 1.5
			"draw_card":
				score += card.effect_value * 3
	
	# 法力曲线考虑
	var cost = card.cost
	if cost <= 3:
		score += 1  # 低费卡容易打出
	elif cost >= 7:
		score += 2  # 高费卡通常更强力
	
	return score

func evaluate_attack_hero(attacker: Control, enemy_health: int) -> float:
	"""评估攻击敌方英雄的价值"""
	var score = attacker.attack * 2.0  # 基础伤害价值
	
	# 如果能击杀敌方英雄，优先级极高
	if attacker.attack >= enemy_health:
		score += 1000
	
	# 如果敌方战场为空，更倾向于攻击英雄
	if GameManager and GameManager.player_board.is_empty():
		score += 3
	
	return score

func evaluate_attack_unit(attacker: Control, target: Control) -> float:
	"""评估攻击敌方单位的价值"""
	var score = 0.0
	
	# 如果能击杀目标且自己不死，优先级很高
	if attacker.attack >= target.health and target.attack < attacker.health:
		score += 15
	
	# 如果能击杀目标但自己也会死，根据价值判断
	elif attacker.attack >= target.health:
		var target_value = target.attack + target.health + target.cost
		var self_value = attacker.attack + attacker.health + attacker.cost
		if target_value >= self_value:
			score += 8  # 值得交换
		else:
			score += 2  # 不太值得
	
	# 如果不能击杀目标，考虑伤害价值
	else:
		score += min(attacker.attack, target.health) * 1.5
	
	# 优先攻击高威胁目标
	score += target.attack * 0.5
	
	# 如果自己会死，减分
	if target.attack >= attacker.health:
		score -= attacker.attack + attacker.health
	
	return score

func execute_action(action: Dictionary, hand: Array[Control], board: Array[Control], mana: int, enemy_board: Array[Control], enemy_health: int) -> bool:
	"""执行AI行动"""
	match action.type:
		AIAction.PLAY_CARD:
			return execute_play_card(action.card, hand)
		
		AIAction.ATTACK_HERO:
			return execute_attack_hero(action.attacker)
		
		AIAction.ATTACK_UNIT:
			return execute_attack_unit(action.attacker, action.target)
		
		AIAction.END_TURN:
			return true
	
	return false

func execute_play_card(card: Control, hand: Array[Control]) -> bool:
	"""执行打出卡牌"""
	if not GameManager or not card:
		return false
	
	# 从AI手牌中移除
	hand.erase(card)
	
	# 通过GameManager打出卡牌
	var success = GameManager.play_card(card, GameManager.PlayerType.AI)
	if success:
		print("AI打出了: ", card.card_name)
	else:
		print("AI打出卡牌失败: ", card.card_name)	
	return success

func execute_attack_hero(attacker: Control) -> bool:
	"""执行攻击英雄"""
	if not GameManager or not attacker:
		return false
	
	# 通过GameManager执行攻击
	GameManager.attack_with_unit(attacker, null, GameManager.PlayerType.AI)
	
	return true

func execute_attack_unit(attacker: Control, target: Control) -> bool:
	"""执行攻击单位"""
	if not GameManager or not attacker or not target:
		return false
	
	# 通过GameManager执行攻击
	GameManager.attack_with_unit(attacker, target, GameManager.PlayerType.AI)
	
	return true

func set_difficulty(new_difficulty: AIDifficulty):
	"""设置AI难度"""
	difficulty = new_difficulty
	adjust_weights_by_difficulty()

func get_ai_stats() -> Dictionary:
	"""获取AI统计信息"""
	return {
		"difficulty": difficulty,
		"thinking_time": thinking_time,
		"max_actions_per_turn": max_actions_per_turn,
		"action_weights": action_weights.duplicate(),
		"card_value_weights": card_value_weights.duplicate()
	}

func debug_ai_decision(hand: Array, board: Array[Control], mana: int, enemy_board: Array[Control], enemy_health: int):
	"""调试AI决策过程"""
	print("=== AI决策调试 ===")
	print("手牌数量: ", hand.size())
	print("战场单位: ", board.size())
	print("当前法力: ", mana)
	print("敌方战场: ", enemy_board.size())
	print("敌方生命: ", enemy_health)
	
	# 评估所有可能的行动
	var action = decide_next_action(hand, board, mana, enemy_board, enemy_health)
	if action:
		print("选择的行动: ", action.type, " 得分: ", action.score)
	else:
		print("没有可执行的行动")
	
	print("==================")

# 预设AI策略
func apply_strategy(strategy_name: String):
	"""应用预设策略"""
	match strategy_name:
		"aggressive":
			# 激进策略：优先攻击英雄
			action_weights[AIAction.ATTACK_HERO] = 15
			action_weights[AIAction.ATTACK_UNIT] = 5
			card_value_weights["attack"] = 3.0
			
		"defensive":
			# 防守策略：优先清理敌方单位
			action_weights[AIAction.ATTACK_UNIT] = 12
			action_weights[AIAction.ATTACK_HERO] = 4
			card_value_weights["health"] = 2.5
			
		"control":
			# 控制策略：优先打出法术和高价值卡牌
			action_weights[AIAction.PLAY_CARD] = 15
			card_value_weights["effect_value"] = 4.0
			
		"balanced":
			# 平衡策略：默认权重
			adjust_weights_by_difficulty()
